package com.java.demo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zhangwj
 * @date 2020/8/17 11:10 上午
 */
public class Demo2 {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(new MyLock(lock, condition)).start();
        new Thread(new MyLock1(lock, condition)).start();
    }
}

class MyLock implements Runnable {

    private Lock lock;

    private Condition condition;

    MyLock(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            System.out.println("开始等待");
            condition.await();
            System.out.println("等待结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class MyLock1 implements Runnable {

    private Lock lock;

    private Condition condition;

    MyLock1(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            System.out.println("睡觉啦");
            Thread.sleep(5000);
            System.out.println("开始发送信号值");
            condition.signal();
            System.out.println("发送信号值结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}